package com.yuanfeng.base.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.base.dto.BaseOssConfigDTO;
import com.yuanfeng.base.entity.BaseOssConfigEntity;
import com.yuanfeng.base.mapper.BaseOssConfigMapper;
import com.yuanfeng.base.service.BaseOssConfigService;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.CommonStatusEnum;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.RedisUtil;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName BaseOssConfigServiceImpl
 * @Description OSS
 * @Author cf
 * @Date 2023/6/21 16:43
 * @Version 1.0
 */
@Service
public class BaseOssConfigServiceImpl extends ServiceImpl<BaseOssConfigMapper, BaseOssConfigEntity> implements BaseOssConfigService {

    @Autowired
    private BaseOssConfigMapper baseOssConfigMapper;

    @Override
    public ResponseResult selectOSSInfoFeign(String ossType) {
        //接收返回信息
        BaseOssConfigEntity ossConfigEntity = new BaseOssConfigEntity();
//        String ossConfigString = RedisUtil.getNoUpdateTime(YFConfig.OSS_CONFIG);
//        if (StringUtils.isNotEmpty(ossConfigString)) {
//            ossConfigEntity = JSONObject.parseObject(ossConfigString, OssConfigEntity.class);
//            return ResponseResult.success(CommonType.initializationStatus.SUCCESS.getCode(), BizCodeEnume.OSS_SUCCESS.getMsg(), ossConfigEntity);
//        }
        //redis 中不存在 查询数据库 存入redis 返回
        ossConfigEntity = baseOssConfigMapper.selectOSSInfo(ossType);
        if (null != ossConfigEntity) {
            RedisUtil.set(YFConfig.OSS_CONFIG, JSONObject.toJSONString(ossConfigEntity));
            return ResponseResult.success(CommonType.initializationStatus.SUCCESS.getCode(), BizCodeEnume.OSS_SUCCESS.getMsg(), ossConfigEntity);
        } else {
            return ResponseResult.fail(CommonType.initializationStatus.FAIL.getCode(), CommonType.initializationStatus.FAIL.getDesc());
        }
    }

    @Override
    public ResponseResult selectOSSInfo(Map<String, Object> param) {
        String token = param.get("token").toString();
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(token);
        if (null != userInfo) {
            //接收返回信息
            BaseOssConfigEntity ossConfigEntity = new BaseOssConfigEntity();
            String ossType = param.get("ossType") == null ? CommonType.ossType.ALIYUN.getDesc() : (String) param.get("ossType");
//            String ossConfigString = RedisUtil.getNoUpdateTime(YFConfig.OSS_CONFIG);
//            if (StringUtils.isNotEmpty(ossConfigString)) {
//                ossConfigEntity = JSONObject.parseObject(ossConfigString, OssConfigEntity.class);
//                return ResponseResult.success(CommonType.initializationStatus.SUCCESS.getCode(), BizCodeEnume.OSS_SUCCESS.getMsg(), ossConfigEntity);
//            }
            //redis 中不存在 查询数据库 存入redis 返回
            ossConfigEntity = baseOssConfigMapper.selectOSSInfo(ossType);
            if (null != ossConfigEntity) {
//                RedisUtil.set(YFConfig.OSS_CONFIG, JSONObject.toJSONString(ossConfigEntity));
                return ResponseResult.success(CommonType.initializationStatus.SUCCESS.getCode(), BizCodeEnume.OSS_SUCCESS.getMsg(), ossConfigEntity);
            } else {
                return ResponseResult.fail(CommonType.initializationStatus.FAIL.getCode(), CommonType.initializationStatus.FAIL.getDesc());
            }
        }
        return ResponseResult.fail(CommonStatusEnum.TOKEN_ERROR.getCode(), CommonStatusEnum.TOKEN_ERROR.getValue());

    }

    /**
     * 查询OSS配置信息
     * @return
     */
    @Override
    public ResponseResult selectGoodsOSSInfo() {
        //接收返回信息
        Map<String,Object> result =new HashMap<>();
        String ossConfigString = RedisUtil.get("OSS_CONFIG");
        if (StringUtils.isNotEmpty(ossConfigString)) {
            result = JSONObject.parseObject(ossConfigString, Map.class);
            return ResponseResult.success(CommonStatusEnum.SUCCESS.getCode(),BizCodeEnume.OSS_SUCCESS.getMsg(),result);
        }
        result= baseOssConfigMapper.selectGoodsOSSInfo();
        //返回给前端的标识 0 初始化成功但无配置信息  1已经存在配置信息并返回  2初始化失败
        Integer flag = 0;
        if(result==null){
            int res=0;
            //oss配置库没有配置信息就初始化数据
            res=baseOssConfigMapper.insertOSSInfo();
            if(res>0){
                int ossID=0;
                ossID= baseOssConfigMapper.getOSSConfigbyId();
                flag=1;
                result.put("ossID",ossID);
                result.put("flag",flag);
                return ResponseResult.success(CommonStatusEnum.SUCCESS.getCode(),BizCodeEnume.OSS_STACT_SUCCESS.getMsg(),result);
            }else{
                flag=2;
                result.put("flag",flag);
                return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.OSS_FAIL.getMsg());
            }
        }else {
            flag=1;
            result.put("flag",flag);
            if (null != result.get("ossBacketName")) {
                RedisUtil.set("OSS_CONFIG", JSONObject.toJSONString(result));
            }
            //oss配置库存在配置信息并返回给前端做展示
            return ResponseResult.success(CommonStatusEnum.SUCCESS.getCode(),BizCodeEnume.OSS_SUCCESS.getMsg(),result);
        }
    }

    @Override
    public ResponseResult updateOssConfig(BaseOssConfigDTO baseOssConfigReq) {
        if (null != baseOssConfigReq && null != baseOssConfigReq.getToken()) {
            //校验token
            String token = baseOssConfigReq.getToken();
            UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(token);
            if (null != userInfo) {
                //修改oss 配置
                this.baseMapper.updateOssConfig(baseOssConfigReq);
                RedisUtil.remove(YFConfig.OSS_CONFIG);
                BaseOssConfigEntity entity = this.baseMapper.selectOne(new LambdaQueryWrapper<BaseOssConfigEntity>()
                        .eq(BaseOssConfigEntity::getOssStates, "01"));
                RedisUtil.set(YFConfig.OSS_CONFIG, JSON.toJSONString(entity));
                return ResponseResult.success();
            }
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
        }
        return ResponseResult.fail(BizCodeEnume.VALID_EXCEPTION);

    }


    @Override
    public ResponseResult updateOssStates(BaseOssConfigDTO param) {
        if (null != param && null != param.getToken()) {
            //校验token
            String token = param.getToken();
            UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(token);
            if (null != userInfo) {
                //修改oss 配置
                this.baseMapper.update(null,new LambdaUpdateWrapper<BaseOssConfigEntity>()
                        .set(BaseOssConfigEntity::getOssStates,param.getOssStates())
                        .eq(BaseOssConfigEntity::getOssId,param.getOssId()));
                //设置启用，将其余配置停用
                if("01".equals(param.getOssStates())){
                    this.baseMapper.update(null,new LambdaUpdateWrapper<BaseOssConfigEntity>()
                            .set(BaseOssConfigEntity::getOssStates,"00")
                            .ne(BaseOssConfigEntity::getOssId,param.getOssId()));
                }else{
                    this.baseMapper.update(null,new LambdaUpdateWrapper<BaseOssConfigEntity>()
                            .set(BaseOssConfigEntity::getOssStates,"01")
                            .ne(BaseOssConfigEntity::getOssId,param.getOssId()));
                }
                RedisUtil.remove(YFConfig.OSS_CONFIG);
                BaseOssConfigEntity entity = this.baseMapper.selectOne(new LambdaQueryWrapper<BaseOssConfigEntity>()
                        .eq(BaseOssConfigEntity::getOssStates, "01"));
                RedisUtil.set(YFConfig.OSS_CONFIG, JSON.toJSONString(entity));
                return ResponseResult.success();
            }
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
        }
        return ResponseResult.fail(BizCodeEnume.VALID_EXCEPTION);
    }

    @Override
    public String queryOssStates() {
        BaseOssConfigEntity entity = this.baseMapper.selectOne(new LambdaQueryWrapper<BaseOssConfigEntity>()
                .eq(BaseOssConfigEntity::getOssStates, "01"));
        return entity.getOssType();
    }

    @Override
    public ResponseResult queryAllOssConfig() {
        List<BaseOssConfigEntity> list = this.baseMapper.selectList(new QueryWrapper<>());
        return ResponseResult.success(list);
    }

}
